/*
 * 新增产品分类
 * @Author: ljb
 * @Date: 2018-03-27 17:53:51
 * @Last Modified by: kanglin
 * @Last Modified time: 2018-09-25 14:17:40
 */
<style lang="less" rel="stylesheet/less" type="text/less" scoped>
    .v-admin-product-category-create {
        width: 400px;
        min-height: 600px;
    }
</style>
<template>
	<div class="v-admin-product-category-create">
		<Row
			type="flex"
			justify="start">
			<i-col push="1">
				<Form
					ref="formValidate"
					:model="formValidate"
					:rules="ruleValidate"
					:label-width="labelWidth()"
					name="create-form">

					<!--<Form-item-->
						<!--:label="$t('category.name')"-->
						<!--prop="name">-->
						<!--<i-input-->
							<!--v-model="formValidate.name"-->
							<!--:placeholder="$t('category.please_enter_name')"-->
							<!--name="create-name"-->
							<!--type="text"/>-->
					<!--</Form-item>-->

					<!--<Form-item-->
						<!--:label="$t('category.category_const')"-->
						<!--prop="const">-->
						<!--<i-input-->
							<!--v-model="formValidate.const"-->
							<!--:placeholder="$t('category.please_enter_const')"-->
							<!--name="create-const"-->
							<!--type="text"/>-->
					<!--</Form-item>-->

          <Form-item
            required
            v-for="lang in languages"
            :key="'create_category_name' + lang.id"
            :label="lang.name"
            :prop="'category_names[' + lang.id + ']'">
            <i-input
              v-model="formValidate.category_names[lang.id]"
              :placeholder="$t('common.placeholder',{'field': lang.name + $t('category.name')})"
              :name="'create-locale-name' + lang.id"
              type="text"/>
          </Form-item>

					<Form-item
						:label="$t('category.icon')"
						prop="icon">
						<Uploader
							ref="icon"
							@on-remove="(file)=>{handleRemove('icon',file)}"
							@on-change="(file)=>{handleChange('icon',file)}">
							{{ $t('common.pic_tip') + $t('category.img_tip') }}
						</Uploader>
					</Form-item>

					<FormItem :label="$t('category.type')">
						<RadioGroup v-model="formValidate.has_asset">
							<Radio label="1">{{ $t('category.makeup') }}</Radio>
							<Radio label="0">{{ $t('category.skincare') }}</Radio>
						</RadioGroup>
					</FormItem>

					<Form-item
						:label="$t('category.priority')"
						prop="priority">
						<InputNumber
							:max="100000"
							:min="0"
							v-model="formValidate.priority"
							:placeholder="$t('category.please_enter_priority')"
							name="create-priority"/>
					</Form-item>

					<Form-item>
						<Button
							type="primary"
							@click="handleSubmit('formValidate')">
							{{ $t('common.submit') }}
						</Button>
						<Button
							type="ghost"
							style="margin-left: 8px"
							@click="handleReset('formValidate')">
							{{ $t('common.reset') }}
						</Button>
					</Form-item>

				</Form>
			</i-col>
		</Row>
	</div>
</template>

<script>

import { validateImage } from 'src/validate'; // 引入校验文件
import labelWidthMixin from 'src/views/mixins/labelWidthMixin';
import Uploader from 'src/views/component/Uploader';

export default {
	name: 'AdminCategoryCreate',
	components: {
		Uploader,
	},
	mixins: [labelWidthMixin],
  props: {
    languages: {
      type: Array,
      required: true,
    }
  },
	data() {
		return {
			formValidate: {
				name: '', // 类别名称

				const: '', // 英文命名

				priority: 0, // 优先级

				icon: '', // 普通图标

				icon_active: '', // 高亮图标

				has_asset: '0', // 关联素材

				parent_id: '0', // 父类ID

        category_names: {}
			}, // 新建产品分类时的表单

			ruleValidate: { // 表单验证规则
				name: [
					{
						required: true,
						message: this.$t('validate.required', { field: this.$t('category.name') }),
						trigger: 'blur,change',
					},
				],
				const: [
					{
						required: true,
						message: this.$t('validate.required', { field: this.$t('category.category_const') }),
						trigger: 'blur,change',
					},
				],
				icon: [
					{ required: true, validator: validateImage, trigger: 'blur,change' },
				],
				icon_active: [
					{ required: true, validator: validateImage, trigger: 'blur,change' },
				],
				priority: [
					{
						required: true,
						type: 'number',
						message: this.$t('validate.required', { field: this.$t('category.priority') }),
						trigger: 'blur,change',
					},
				],
			},

			// 上传的普通图标信息
			icon_info: {

				name: '',

				url: '',

			},

			// 上传的高亮图标信息
			icon_active_info: {

				name: '',

				url: '',

			},


		};
	},
  mounted() {
	  this.addLocaleValidateRules();
  },
	methods: {
    addLocaleValidateRules() {
      this.languages.forEach(lang => {
        this.ruleValidate['category_names[' + lang.id + ']'] = [
          {
            required: true,
            message: this.$t('validate.required', { field: this.$t('category.name') }),
            trigger: 'blur,change',
          },
        ]
      });
    },
		/**
		 * 选择图片
		 * @param {Object} file {选择的文件对象集合}
		 * @param {String} field {icon}
		 * @return {undefined}
		 */
		handleChange(field, { file }) {
			this.formValidate[field] = file;
			this.$refs.formValidate.validateField(field);
		},

		/**
		 * 删除图片
		 * @param {String} field {icon}
		 * @return {undefined}
		 */
		handleRemove(field) {
			this.formValidate[field] = null;
			this.$refs.formValidate.validateField(field);
		},

    /**
     * 提交表单
     * @param  {string} name {表单的ref}
     * @return {undefined}
     */
		handleSubmit(name) {
			this.$refs[name].validate((valid) => {
				if (valid) {
					this.formDataCreate();
				} else {
					this.$Message.error(this.$t('common.exist_empty_field'));
				}
			});
		},

		/**
     * 重置表单
     * @param  {string} name {表单的ref}
     * @return {undefined}
     */
		handleReset(name) {
			this.$refs.icon.reset();

			this.$refs[name].resetFields();

			this.icon_info.name = '';

			this.icon_info.url = '';
		},

		/**
     * 手动拼接表单数据
     * @return {Object} {拼接好的表单数据}
     */
		formDataCreate() {
			const new_object = {
				name: this.formValidate.name,

				const: this.formValidate.const,

				priority: this.formValidate.priority,

				icon: this.formValidate.icon,

				icon_active: this.formValidate.icon_active,

				has_asset: this.formValidate.has_asset,

				parent_id: this.formValidate.parent_id,
			};

			Object.keys(this.formValidate.category_names).forEach((lang_id, idx) => {
        new_object[`category_names[${idx}][language_id]`] = lang_id;
        new_object[`category_names[${idx}][name]`] = this.formValidate.category_names[lang_id];
      })

			const form_data = new FormData();

			Object.keys(new_object).forEach((key) => {
				form_data.append(key, new_object[key]);
			});

      console.log(form_data)

      this.$emit('post', form_data);
		},

	},
};
</script>
